﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using Jb.Common.Extensions;
using Jb.Domain;
using Jb.Web.ViewModels;
using Jb.Web.Utility;
using AutoMapper;
using Jb.Web.ViewModels.UtilityModels;


namespace Jb.Web.Areas.JobSeeker.Controllers
{
    [Authorize(Roles = "Job Seeker,Admin")]
    public class CoverLetterController : BaseController
    {
		private JbEntities _Context = new JbEntities();
        
		#region Constructors
		public CoverLetterController()
		{
		}

		public CoverLetterController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods
        public ActionResult Index()
        {
            return View("list", BuildCoverLetterListConfig());
        }
        public ActionResult List()
        {
            return View(BuildCoverLetterListConfig());
        }
        
		/// <summary>
        /// Gets a CoverLetter from Database to edit
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
		public ActionResult Edit(int id = 0, String IsSaved = null)
        {
            CoverLetter entity = null;
            if (id == 0)
            {
                entity = new CoverLetter();
                entity.JobSeekerID = LoggedInUser.JobSeekerID;
            }
            else
            {
                entity = _Context.CoverLetters.FirstOrDefault(P => P.ID == id);
                if (entity != null && entity.JobSeekerID != LoggedInUser.JobSeekerID)
                    return base.RedirectToAccessDenied();
            }

            CoverLetterViewModel viewModel = Mapper.Map<CoverLetter, CoverLetterViewModel>(entity);
            if (String.Compare(IsSaved, "true", true) == 0)
                ViewData[AppConstants.ViewDataKeys.SAVED] = true;

            return View(viewModel);
        }

		/// <summary>
        /// Saves CoverLetter Information into the Database
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
		[HttpPost]
		public ActionResult Edit(CoverLetterViewModel viewModel)
        {
			if (!ModelState.IsValid)
                return View(viewModel);

            if (viewModel.JobSeekerID != LoggedInUser.JobSeekerID) ///Probable hacking attempt
                return base.RedirectToAccessDenied();

			CoverLetter entity = null; 
			if (viewModel.ID == 0)
            {
                entity = new CoverLetter();
                _Context.AddToCoverLetters(entity);
            }
            else
                entity = _Context.CoverLetters.FirstOrDefault(P => P.ID == viewModel.ID);

            entity = Mapper.Map<CoverLetterViewModel, CoverLetter>(viewModel, entity);
            //entity.JobSeekerID = LoggedInUser.JobSeekerID;
		
            _Context.SaveChanges();
            return RedirectToAction(String.Format("Edit/{0}", entity.ID), new { IsSaved = "true" });
            //return RedirectToAction("Index");
        }

        /// <summary>
        /// Delets a coverletter fro this job seeker.
        /// </summary>
        /// <param name="id"></param>
        /// <returns>
        /// -1 > If the coverletter is not belong to this job seeker. Probable hacking attempt.
        /// -2 > If the requested coverletter was not found for delete.
        /// +1 > Deleted successfully.
        /// </returns>
        [HttpPost]
        public int Delete(int id)
        {
            CoverLetter coverLetter = _Context.CoverLetters.FirstOrDefault(P => P.ID == id);
            if (coverLetter == null)
                return -2;
            else if (coverLetter.JobSeekerID != LoggedInUser.JobSeeker.ID)
                return -1;
            else
            {
                _Context.DeleteObject(coverLetter);
                _Context.SaveChanges();
                return 1;
            }
        }
		#endregion Action Methods
		
		#region Helper Methods

        /// <summary>
        /// Builds a list of coverletters of currently logged in Job Seeker
        /// </summary>
        /// <returns></returns>
        private ListConfig BuildCoverLetterListConfig()
        {
            UtilityDAO dao = new UtilityDAO();
            Jb.Domain.DbParameter[] parameters = new[]{
                new Jb.Domain.DbParameter("@JobSeekerID", LoggedInUser.JobSeekerID)
            };
            DataSet ds = dao.GetDataSet(DbObject.SP.GET_COVERLETTERS_BY_JOBSEEKER, parameters, true);
            ListConfig listConfig = new ListConfig(ds.Tables[0], null);
            return listConfig;
        }

        #endregion			
    }
}


